// pages/start/start.js
const app = getApp()
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    is_android: true,
    is_hidden: true,
    loading: true,
    img: [
      "https://z3.ax1x.com/2021/05/30/2Vmaef.png",
      "https://z3.ax1x.com/2021/05/30/2VmQoD.png"
    ],
    ColorList: app.globalData.ColorList,
    color: 'red',
    show_login:false,
    token: wx.getStorageSync('token'),
    user: wx.getStorageSync('user'),
    elements: [{
      title: '布局',
      name: 'layout',
      color: 'blue',
      icon: 'newsfill'
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  this.getTopImg()
  this.getSchoolInfo()
  this.setData({loged:wx.getStorageSync('loged')})
  if (wx.getStorageSync('loged')) {
    this.getUserinfo()
    this.setData({
      phoneos: wx.getStorageSync('os'),
      loged: wx.getStorageSync('loged'),
      token: wx.getStorageSync('token'),
      user: wx.getStorageSync('user'),
      userinfo: wx.getStorageSync('userinfo'),
    })
    wx.stopPullDownRefresh()
  }
  },
  shouquan(){
    wx.requestSubscribeMessage({
      tmplIds: ['ejT7D2ryZ2w-DEYOdZSa2fnMN-KqGjpIsrPzewMfWTk'],
      success (res) {
        console.log(res)
        wx.showToast({
        title: '订阅成功',
      })}
      })
  },
  send(){
  wx.cloud.callFunction({
    name:'sendMsg'
  }).then(res=>{
    console.log(res)
  })
  },
  write(){
  db.collection('p_pushlist').add({
    data:{
    os: wx.getStorageSync('os'),
    token: wx.getStorageSync('token'),
    userId: wx.getStorageSync('user').id
    }
  }).then(res=>{
    console.log(res)
    wx.showToast({
      title: '订阅成功',
    })
  })
  },
showTips(){
wx.showModal({
  title:'用户须知',
  content:'IOS端新用户可使用安卓手机注册账号并充值余额后在本程序消费充电！IOS端老用户请点击上方Andrid徽标切换系统后登录本程序。'
})
},
  getUserinfo() {
    wx.cloud.callFunction({
      name: "userInfo",
      data: {
        os: this.data.is_android ? 'android' : 'ios',
        userId: this.data.userId,
        token: this.data.token
      }
    }).then(res => {
      wx.hideLoading()
      console.log("成功", res)
      let bkdata = JSON.parse(res.result)
      if (bkdata.code == 0) {
        bkdata.data.amount = bkdata.data.amount.toFixed(2)
        this.setData({
          userinfo: bkdata.data
        })
        wx.setStorageSync('userinfo', bkdata.data)
      } else {
        wx.showToast({
          title: bkdata.msg,
          icon: 'none'
        })
      }
    }).catch(res => {
      console.log("失败", res)
      wx.showToast({
        title: '系统错误！',
        icon: 'none'
      })
    })
  },
  getTopImg() {
    db.collection('p_carousel').get()
      .then(res => {
        console.log(res)
        this.setData({
          imgList: res.data
        })
      })
  },
  getSchoolInfo(){
  db.collection('p_schoolinfo').get().then(res=>{
    console.log(res)
    this.setData({
      infoList : res.data
    })
  })
  },
  showInfo(e){
    console.log(e)
  let info = e.currentTarget.dataset.info
  wx.showModal({
   title: info.title,
   content: info.detail
  })
  },
  showModal(e) {
    console.log(e)
    this.setData({
      modalName: 'Image',
      url: e.currentTarget.dataset.url
    })
  },
  showCard(e) {
    console.log(e)
    if(wx.getStorageSync('loged')){
      this.setData({
        is_hidden: false
        })
    }else{

      this.setData({
       show_login: true
      })
    }
    
  },
  modelCancel(){
    this.setData({
      is_hidden: true,
      show_login: false
      })
  },
 logOut(){
    wx.showModal({
     title:'是否退出',
     content:"是否注销本系统的登录状态并清空当前账号的数据？",
    }).then(res=>{
      if(res.confirm){
        wx.clearStorage()
        this.setData({
        is_hidden: true,
        show_login: false
        })
        this.onLoad()
      }else{
        this.setData({
          is_hidden: true,
          show_login: false
          })
      }
     
      
    })
  
  },
  hideModal(e) {
    this.setData({
      modalName: null, 
      url:''
    })
  },
  phoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  pwdInput(e) {
    this.setData({
      pwd: e.detail.value
    })
  },
  toLogin() {
    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon:'none'
      })
    } else if (!this.data.pwd) {
      wx.showToast({
        title: '请输入登录密码',
        icon:'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
      })
      wx.cloud.callFunction({
        name: "login",
        data: {
          os: this.data.is_android ? 'android' : 'ios',
          phone: this.data.phone,
          pwd: this.data.pwd
        }
      }).then(res => {
        wx.hideLoading()
        console.log("成功", res)
        let bkdata = JSON.parse(res.result)
        if (bkdata.code == 0) {
          wx.showToast({
            title: '登录成功',
            icon: 'none'
          })
          wx.setStorageSync('os', this.data.is_android ? 'android' : 'ios')
          wx.setStorageSync('token', bkdata.data.token)
          wx.setStorageSync('user', bkdata.data.user)
          wx.setStorageSync('loged', true)
          this.setData({
            is_hidden: true,
            user: bkdata.data.user,
            loged: wx.getStorageSync('loged')
          })
          wx.cloud.callFunction({
            name: "userInfo",
            data: {
              os: this.data.is_android ? 'android' : 'ios',
              userId: wx.getStorageSync('user').id,
              token: wx.getStorageSync('token'),
            }
          }).then(res => {
            wx.hideLoading()
            this.setData({
             show_login:false
            })
            console.log("成功", res)
            let bkdata = JSON.parse(res.result)
            if (bkdata.code == 0) {
              bkdata.data.amount = bkdata.data.amount.toFixed(2)
              this.setData({
                userinfo: bkdata.data
              })
              wx.setStorageSync('userinfo', bkdata.data)
              this.getPowerOrder()
            } else {
              wx.showToast({
                title: bkdata.msg,
                icon: 'none'
              })
            }
          }).catch(res => {
            console.log("失败", res)
            wx.showToast({
              title: '系统错误！请下拉刷新当前页面',
              icon: 'none'
            })
          })
        } else {
          this.setData({
            show_login:false
          })
          wx.showToast({
            title: bkdata.msg,
            icon: 'none'
          })
        }
      }).catch(res => {
        console.log("失败", res)
        this.setData({
          show_login:false
        })
        wx.showToast({
          title: '系统错误！',
          icon: 'none'
        })
      })
    }
  },

  changeSchool(){
  wx.showActionSheet({
    itemList: ['山东理工大学西校区','山东理工大学东校区'],
  }).then(res=>{
   console.log(res)
   if(res.tapIndex == 0){
     this.setData({area:'山东理工大学西校区'})
   }else{
    this.setData({area:'山东理工大学东校区'})
    wx.showToast({
      title: '东校数据还未采集呢，如果您想帮忙采集数据，请联系我的微信哦，不胜感激~',
      icon:'none'
    })
   }
  })
  },
  changeOs() {
    this.setData({
      is_android: !this.data.is_android
    })
  },
  navToOrder() {
    if(wx.getStorageSync('loged')){
       wx.navigateTo({
      url: '/pages/order/order',
    })
    }else{
      wx.showToast({
        title: '您还未登录哦~',
        icon:'none'
      })
      this.setData({
        show_login:true
      })
    }
   
  },
  navTo(e){
  wx.navigateTo({
    url: e.currentTarget.dataset.path,
  })
  },
    //展示分享弹窗
    showShare() {
      this.setData({
            showShare: true
      });
},
//关闭弹窗
closePop() {
      this.setData({
            showShare: false,
      });
},
//预览图片
preview(e) {
      wx.previewImage({
            urls: e.currentTarget.dataset.link.split(",")
      });
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.onLoad()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
   
  },
  onShareTimeline: function (res) {
    
  },
})